package com.moss.street.market;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * A servlet that is used to check whether a booking is possible for a specific
 * stall and date.  Acts as a controller for the Welcome.jsp web page.
 * 
 * @author drusk
 *
 */
public class CheckBookingsServlet extends HttpServlet implements Servlet
{
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        String stall = request.getParameter("stall_number");
        String[] marketdays = request.getParameterValues("marketday");
        String marketday = null;
        
        // TODO: Handle an array of market day requests
        // MarketDayServlet would need to have option 'multiple'
        // as in <select name=\"marketday\" multiple size=\"10\">
        // and consequences of one or more unavailable days need
        // to be decided upon.
        if (marketdays != null && marketdays.length > 0) {
        	marketday = marketdays[0];
        }
        
    	Connection conn = DerbyDatabase.getConnInstance();
        if ((stall != null) && (marketday != null)) {
            Boolean available = DerbyDatabase.isStallAvailable(conn, stall, marketday);
            StallsBean availableStall = DerbyDatabase.getStallDetails(conn, stall);
            if (availableStall == null) {
            	System.err.println("availableStall is null");
            }
            request.setAttribute("stall_number", stall);
            request.setAttribute("marketday", marketday);
            if (!available)
            {
                request.setAttribute("stallnotavailable", "true");
                getServletContext().getRequestDispatcher("/Welcome.jsp").forward(request, response); 
            } else {
                request.getSession().setAttribute("stall", availableStall);
                getServletContext().getRequestDispatcher("/BookStall.jsp").forward(request, response);
            }
        } else if (stall != null) {
        	// want to know dates when a specific stall is available
        	BookingsBean stallBookings[] = DerbyDatabase.fetchBookingsByStall(conn, stall);
        	List<String> bookedDates = new ArrayList<String>();
        	if (stallBookings != null) {
        		for (int i = 0; i < stallBookings.length; i++) {
        			bookedDates.add(stallBookings[i].getDateReserved());
        		}
        	}
           	
        	Calendar c = Calendar.getInstance();
    		// Set the calendar to SATURDAY of the current week
    		c.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);

    		// Print upcoming Saturdays starting with current week
    		// for the next year
    		DateFormat df = new SimpleDateFormat("EEE dd-MMM-yyyy");
    		DateFormat dfdb = new SimpleDateFormat("yyyy-MM-dd");
    		
           	List<String> sb = new ArrayList<String>();
       		sb.add("<table width=\"50%\" border=\"1\" bordercolor=\"#FFFFFF\" class=\"body\">\n");
    		sb.add("<tr>");
    		sb.add("<td width=\"25%\" bgcolor=\"#DDDDFF\"><b>Date</b></td>");
    		sb.add("</tr>");
    		for (int i = 0; i <= 52; i++) {
    			if (bookedDates != null && bookedDates.size() > 0 &&
    					bookedDates.contains(dfdb.format(c.getTime()))) {
    				sb.add("<tr>");
    				sb.add("<td width=\"25%\" bgcolor=\"#FF0000\">"+df.format(c.getTime())+"</td>");
    				sb.add("</tr>");
    			} else {
    				sb.add("<tr>");
    				sb.add("<td width=\"25%\" bgcolor=\"#FFFFF\">"+df.format(c.getTime())+"</td>");
    				sb.add("</tr>");
    			}
    			c.add(Calendar.DATE, 7);
    		}
    		sb.add("</table>");
    		request.setAttribute("stallnumber", stall);
        	request.getSession().setAttribute("stringarray", sb);
        	getServletContext().getRequestDispatcher("/AvailabilityByStall.jsp").forward(request, response);
        } else if (marketday != null) {
        	// wants to know which stalls are available on a specific date
        	request.setAttribute("marketday", marketday);
           	BookingsBean stallBookings[] = DerbyDatabase.fetchBookingsByDate(conn, marketday);
           	List<String> bookedStallNums = new ArrayList<String>();
           	if (stallBookings != null) {
           		for (int i = 0; i < stallBookings.length; i++) {
           			bookedStallNums.add(stallBookings[i].getStallNumber());
           		}
           	}
           	StallsBean allStalls[] = DerbyDatabase.stallsList(conn);
           	List<String> sb = new ArrayList<String>();
           	
        	if (allStalls != null) {
        		sb.add("<table width=\"100%\" border=\"1\" bordercolor=\"#FFFFFF\" class=\"body\">\n");
        		sb.add("<tr>");
        		sb.add("<td width=\"5%\" bgcolor=\"#DDDDFF\"><b>Stall Number</b></td>");
        		sb.add("<td width=\"15%\" bgcolor=\"#FFFFFF\"><b>Stall Type</b></td>");
        		sb.add("<td width=\"12%\" bgcolor=\"#DDDDFF\"><b>Length (cm)</b></td>");
        		sb.add("<td width=\"12%\" bgcolor=\"#FFFFFF\"><b>Width (cm)</b></td>");
        		sb.add("<td width=\"12%\" bgcolor=\"#DDDDFF\"><b>Fee (CDN$)</b></td>");
        		sb.add("</tr>");
        		for (int i = 0; i < allStalls.length; i++) {
        			if (bookedStallNums != null && bookedStallNums.size() > 0 &&
        					bookedStallNums.contains(allStalls[i].getStallNumber())) {
        				sb.add("<tr>\n");
        				sb.add("<td width=\"5%\" bgcolor=\"#FF0000\">"+allStalls[i].getStallNumber()+"</td>\n");
        				sb.add("<td width=\"15%\" bgcolor=\"#FF0000\">"+allStalls[i].getStallType()+"</td>\n");
        				sb.add("<td width=\"12%\" bgcolor=\"#FF0000\">"+allStalls[i].getLength()+"</td>\n");
        				sb.add("<td width=\"12%\" bgcolor=\"#FF0000\">"+allStalls[i].getWidth()+"</td>\n");
        				sb.add("<td width=\"12%\" bgcolor=\"#FF0000\">"+allStalls[i].getFee()+"</td>\n");
        				sb.add("</tr>\n");
        			} else {
        				sb.add("<tr>\n");
           				sb.add("<td width=\"5%\" bgcolor=\"#FFFFFF\">"+allStalls[i].getStallNumber()+"</td>\n");
        				sb.add("<td width=\"15%\" bgcolor=\"#FFFFFF\">"+allStalls[i].getStallType()+"</td>\n");
        				sb.add("<td width=\"12%\" bgcolor=\"#FFFFFF\">"+allStalls[i].getLength()+"</td>\n");
        				sb.add("<td width=\"12%\" bgcolor=\"#FFFFFF\">"+allStalls[i].getWidth()+"</td>\n");
        				sb.add("<td width=\"12%\" bgcolor=\"#FFFFFF\">"+allStalls[i].getFee()+"</td>\n");
        				sb.add("</tr>\n");
        			}
        		}
        		sb.add("</table>\n");
        	}
        	request.getSession().setAttribute("stringarray", sb);
        	getServletContext().getRequestDispatcher("/AvailabilityByDate.jsp").forward(request, response);
        } else {
        	// didn't select either stall or marketday
            getServletContext().getRequestDispatcher("/Welcome.jsp").forward(request, response);
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    		throws ServletException, IOException {
            doPost(request,response);
    }
}
